package pl.edu.mimuw.irs.core.model.analysis;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

public class Registry implements IRegistry {

	// *** Attributes
	
	private Map<Object, Set<IListener>> registry;
	public Map<Object, Set<IListener>> getRegistry() {
		if (registry == null) registry = new LinkedHashMap<Object, Set<IListener>>();
		return registry;
	}

	// *** Methods
	
	@Override
	public void register(Object propertyId, IListener listener) {
		Set<IListener> listeners = getRegistry().get(propertyId);
		if (listeners == null) {
			listeners = new LinkedHashSet<IListener>();
			getRegistry().put(propertyId, listeners);
		}
		listeners.add(listener);
	}
	
	@Override
	public void unregister(Object propertyId, IListener listener) {
		Set<IListener> listeners = getRegistry().get(propertyId);
		if (listeners != null) {
			listeners.remove(listener);
			if (listeners.size() == 0) getRegistry().remove(propertyId);
		}
	}
	
	private Set<IListener> getListeners(Object propertyId) {
		Set<IListener> listeners = getRegistry().get(propertyId);
		if (listeners == null) listeners = new HashSet<IListener>();
		return listeners;
	}
	
	@Override
	public void notifyListeners(Object propertyId, Object newValue, IRegistry registry) {
		Set<IListener> listeners = getListeners(propertyId);
		for (IListener listener : listeners) {
			listener.propertyChanged(propertyId, newValue, registry);
		}
	}
	
	@Override
	public boolean isRegistered(Object propertyId, IListener listener) {
		return getListeners(propertyId).contains(listener);
	}
}
